#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;

int cnt = 0;

//静态初始化 ——锁和条件变量
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


void *Count(void* args)
{
    pthread_detach(pthread_self());

    uint64_t num = (uint64_t)args;
    cout << "thread " << num << "create success" << endl;

    while(true)
    {
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond,&lock); // pthread_cond_wait让线程等待的时候，会自动释放锁
        cout << "thread num is : " << num << " cnt :" << cnt++ << endl;
        pthread_mutex_unlock(&lock);
    }

    return nullptr;
}

int main()
{
    for(uint64_t i = 0; i < 5; i++)
    {
        pthread_t tid;
        pthread_create(&tid,nullptr,Count,(void* )i);//这里i不需要&，需要传的是它的拷贝。
        usleep(1000);
    }

    sleep(3);
    cout << "main thread ctrl beign : " << endl;

    while(1) 
    {
        sleep(1);
        //pthread_cond_signal(&cond);// 唤醒等待队列中等待的线程，默认是队头线程
        pthread_cond_broadcast(&cond);
        cout << "signal one thread~" << endl;
    }

    return 0;
}